package com.crm.api.service.impl;

import com.crm.api.entity.Employee;
import com.crm.api.mapper.EmployeeMapper;
import com.crm.api.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工服务实现类
 */
@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> getEmployees(Integer page, Integer size, String realName, 
                                          String username, String department, String position, 
                                          String role, Boolean isActive) {
        
        // 计算偏移量
        Integer offset = (page - 1) * size;
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", size);
        params.put("limit", size);  // 为了兼容性保留
        params.put("realName", realName);
        params.put("username", username);
        params.put("department", department);
        params.put("position", position);
        params.put("role", role);
        params.put("isActive", isActive);
        
        // 查询数据
        List<Employee> employees = employeeMapper.findEmployees(params);
        Integer total = employeeMapper.countEmployees(params);
        
        // 清除密码字段
        employees.forEach(employee -> employee.setPassword(null));
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("data", employees);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (total + size - 1) / size);
        
        return result;
    }

    @Override
    public Employee getEmployeeById(Integer id) {
        return employeeMapper.findById(id);
    }

    @Override
    public Employee getEmployeeByUsername(String username) {
        return employeeMapper.findByUsername(username);
    }

    @Override
    public Employee createEmployee(Employee employee) {
        // 生成员工编号
        if (employee.getEmployeeCode() == null || employee.getEmployeeCode().trim().isEmpty()) {
            String employeeCode = generateEmployeeCode();
            employee.setEmployeeCode(employeeCode);
        }
        
        // 加密密码
        if (employee.getPassword() == null || employee.getPassword().trim().isEmpty()) {
            employee.setPassword("123456"); // 默认密码
        }
        employee.setPassword(passwordEncoder.encode(employee.getPassword()));
        
        // 设置默认值
        if (employee.getIsActive() == null) {
            employee.setIsActive(true); // 默认在职
        }
        if (employee.getRole() == null || employee.getRole().trim().isEmpty()) {
            employee.setRole("employee"); // 默认角色
        }
        
        // 设置创建时间
        employee.setCreatedAt(new Date());
        employee.setUpdatedAt(new Date());
        
        // 插入数据
        employeeMapper.insert(employee);
        
        return employee;
    }

    @Override
    public Employee updateEmployee(Employee employee) {
        // 检查员工是否存在
        Employee existingEmployee = employeeMapper.findById(employee.getId());
        if (existingEmployee == null) {
            return null;
        }
        
        // 如果提供了新密码，则加密
        if (employee.getPassword() != null && !employee.getPassword().trim().isEmpty()) {
            employee.setPassword(passwordEncoder.encode(employee.getPassword()));
        } else {
            // 保持原密码
            employee.setPassword(existingEmployee.getPassword());
        }
        
        // 设置更新时间
        employee.setUpdatedAt(new Date());
        
        // 更新数据
        employeeMapper.update(employee);
        
        return employeeMapper.findById(employee.getId());
    }

    @Override
    public boolean deleteEmployee(Integer id) {
        // 检查员工是否存在
        Employee employee = employeeMapper.findById(id);
        if (employee == null) {
            return false;
        }
        
        // 删除员工
        employeeMapper.deleteById(id);
        return true;
    }

    @Override
    public boolean resetPassword(Integer id, String password) {
        // 检查员工是否存在
        Employee employee = employeeMapper.findById(id);
        if (employee == null) {
            return false;
        }
        
        // 加密密码并更新
        String encodedPassword = passwordEncoder.encode(password);
        employeeMapper.updatePassword(id, encodedPassword);
        return true;
    }

    @Override
    public boolean updateEmployeeStatus(Integer id, Boolean isActive) {
        // 检查员工是否存在
        Employee employee = employeeMapper.findById(id);
        if (employee == null) {
            return false;
        }
        
        // 更新状态
        employeeMapper.updateStatus(id, isActive, new Date());
        return true;
    }

    @Override
    public List<String> getDepartments() {
        return employeeMapper.findDistinctDepartments();
    }

    @Override
    public List<String> getPositions() {
        return employeeMapper.findDistinctPositions();
    }

    @Override
    public boolean existsByUsername(String username) {
        return employeeMapper.existsByUsername(username) > 0;
    }

    @Override
    public boolean existsByUsernameAndNotId(String username, Integer id) {
        return employeeMapper.existsByUsernameAndNotId(username, id) > 0;
    }

    @Override
    public boolean existsByEmployeeCode(String employeeCode) {
        return employeeMapper.existsByEmployeeCode(employeeCode) > 0;
    }

    @Override
    public boolean existsByEmployeeCodeAndNotId(String employeeCode, Integer id) {
        return employeeMapper.existsByEmployeeCodeAndNotId(employeeCode, id) > 0;
    }

    @Override
    public boolean hasRelatedBusinesses(Integer id) {
        return employeeMapper.countRelatedBusinesses(id) > 0;
    }

    @Override
    public boolean hasRelatedWorkOrders(Integer id) {
        return employeeMapper.countRelatedWorkOrders(id) > 0;
    }

    /**
     * 生成员工编号
     */
    private String generateEmployeeCode() {
        // 获取当前最大编号
        String maxCode = employeeMapper.getMaxEmployeeCode();
        
        if (maxCode == null) {
            return "EMP002"; // 从EMP002开始，因为EMP001已经被admin占用
        }
        
        // 提取数字部分
        String numberPart = maxCode.substring(3);
        int number = Integer.parseInt(numberPart) + 1;
        
        // 格式化为3位数字
        return String.format("EMP%03d", number);
    }
}